{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "06543909",
   "metadata": {},
   "source": [
    "## 易错点：\n",
    "    折线图是plt.plot(X数据,Y数据，颜色)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "04c4537d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "745b6868",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('./data/data_cluster.csv',encoding='gbk',header=0)\n",
    "df =df.sample(1000)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4ef7ac0",
   "metadata": {},
   "source": [
    "1, 使用MinMaxScaler函数对数据进行归一化处理，将数据存储为df_norm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d84ab41d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52eedf17",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_mm = MinMaxScaler()\n",
    "df_norm = model_mm.fit_transform(df)\n",
    "df_norm = pd.DataFrame(data=df_norm,columns=df.columns)\n",
    "df_norm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d220315",
   "metadata": {},
   "source": [
    "2.使用SpecteralClustering 算法选择K值2-12对数据进行聚类分析，使用轮廓系数进行评估，将轮廓系数和K值存储在列表k和silhouette_s中，并绘制折线图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "12024391",
   "metadata": {},
   "outputs": [],
   "source": [
    "#由考生填写\n",
    "from sklearn.cluster import SpectralClustering\n",
    "from sklearn.metrics import silhouette_score\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3e8c5b86",
   "metadata": {},
   "outputs": [],
   "source": [
    "#由考生填写\n",
    "k,silhouette = [],[]\n",
    "for i in range(2,13):\n",
    "    sc_model = SpectralClustering(n_clusters=i)\n",
    "    sc_model.fit(X=df_norm)\n",
    "    result = sc_model.labels_\n",
    "    k.append(i)\n",
    "    s = silhouette_score(df_norm,result)\n",
    "    silhouette.append(s)\n",
    "# 设置中文字体\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "#由考生填写\n",
    "plt.figure()\n",
    "plt.title('SpectralClustering')\n",
    "#由考生填写\n",
    "plt.plot(k,silhouette,'r')\n",
    "plt.xlabel('聚类的簇数')\n",
    "plt.ylabel('轮廓系数')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PySpark-2.4.5",
   "language": "python",
   "name": "pyspark-2.4.5"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
